package com.open.capacity.finance.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.common.config.ServerConfig;
import com.open.capacity.commons.Result;
import com.open.capacity.finance.dao.AuditModelWarnDao;
import com.open.capacity.finance.dto.AuditModelBaseResult;
import com.open.capacity.finance.entity.AuditModelWarn;
import com.open.capacity.finance.service.AbstractAuditMakeResultFactory;
import com.open.capacity.finance.service.AuditModelWarnService;
import com.open.capacity.finance.util.FileUtil;
import com.open.capacity.model.system.LoginAppUser;
import com.open.capacity.user.model.SysCompany;
import com.open.capacity.utils.SysUserUtil;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.list.TreeList;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import com.open.capacity.finance.entity.AuditModel;
import com.open.capacity.finance.service.AuditModelService;

import com.open.capacity.commons.PageResult;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 审计模型
 *
 * @author
 * @email
 * @date 2023-02-01 09:14:56
 */
@Slf4j
@RestController
@RequestMapping("auditmodels")
@Api(tags = "审计模型")
public class AuditModelController {


    @Autowired
    private AuditModelService auditModelService;

    @Autowired
    private AuditModelWarnService warnService;

    @Autowired
    private ServerConfig serverConfig;

    @Value("${file.uploadpath:/usr/local/files}")
    public String fileuploadPath;


    /**
     * 列表
     */
    @RequestMapping("/list")
    @PreAuthorize("hasAnyAuthority('audit_model:auditmodel:list')")
    public PageResult list(@RequestParam Map<String, Object> params) {
        PageResult pageResult = auditModelService.pageAll(params);
        return pageResult;
    }

    @PreAuthorize("hasAnyAuthority('audit_model:auditmodel:list')")
    @GetMapping("/dropdownList")
    public Result<List<TreeVo>> dropdownList(@RequestParam(value = "parentId", defaultValue = "0") String parentId) {
        Map<String, Object> params = new HashMap<>();
        params.put("status", 1);
        List<AuditModel> list = new ArrayList<>();
        AuditModel all = new AuditModel();
        all.setId("");
        all.setCode("");
        all.setName("所有指标模型");
        all.setCodeAndName("所有指标模型");
        list.add(all);
        list.addAll(auditModelService.findAll(params));
        List<TreeVo> dropdownList = new TreeList();
        list.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getCodeAndName());
            node.setTitle(m.getCodeAndName());
            node.setValue(m.getId().toString());
            node.setShowcheck(false);
            node.setCheckstate(0);
            node.setIsexpand(true);
            node.setComplete(false);
            node.setParentId("");
            dropdownList.add(node);
        });

        return Result.succeed(dropdownList);
    }

    /**
     * 查询单条记录
     */
    @RequestMapping("/findById")
    @PreAuthorize("hasAnyAuthority('audit_model:auditmodel:list')")
    public Result findById(String id) {
        return Result.succeed(auditModelService.findById(id));
    }


    /**
     * 查询单条记录
     */
    @RequestMapping("/findByIds")
    @PreAuthorize("hasAnyAuthority('audit_model:auditmodel:list')")
    public Result findByIds(String ids) {
        return Result.succeed(auditModelService.findByIds(ids));
    }


    /**
     * 保存
     */
    @RequestMapping("/saveOrUpdate")
    @PreAuthorize("hasAnyAuthority('audit_model:auditmodel:save')")
    @LogAnnotation(module = "模型", name = "编辑")
    public Result save(@RequestBody @Valid AuditModel auditModel, String keyValue) {
        if (StringUtils.isEmpty(keyValue)) {
            auditModelService.save(auditModel);
        } else {
            auditModel.setId(keyValue);
            auditModelService.update(auditModel);
        }
        return Result.succeed("保存成功");
    }

    /**
     * 更新状态
     */
    @PostMapping(value = "/{id}/updateStatus")
    @LogAnnotation(module = "模型", name = "更新状态")
    public Result updateStatus(@PathVariable(value = "id") String id, Integer status) {
        auditModelService.updateStatus(id, status);
        return Result.succeed(null, "更新成功");
    }


    /**
     * 删除
     */
    @RequestMapping("/delete/{id}")
    @PreAuthorize("hasAnyAuthority('audit_model:auditmodel:delete')")
    @LogAnnotation(module = "模型", name = "删除")
    public Result delete(@PathVariable String id) {
        auditModelService.delete(id);
        return Result.succeed("删除成功");
    }


    /**
     * 执行分析
     */
    @RequestMapping("/analyse")
    @PreAuthorize("hasAnyAuthority('audit_model:auditmodel:analyse')")
    public Result analyseModel(String modelId, String companyId, Map<String, Object> param) {
        Assert.isTrue(StringUtils.isNotEmpty(modelId), "请选择需要执行分析的模型");
        String[] idArrs = modelId.split(",");

        auditModelService.analyseModel(Arrays.asList(idArrs), companyId, param);
        return Result.succeed("执行完成");
    }

    /**
     * 执行分析
     */
    @RequestMapping("/previewResult")
    @PreAuthorize("hasAnyAuthority('audit_model:auditmodel:previewResult')")
    public Result previewResult(@RequestParam Map<String, Object> param) {
        String modelId = param.get("modelId").toString();
        String warnId = param.containsKey("warnId") ? param.get("warnId").toString() : null;

        AuditModelBaseResult result = auditModelService.previewResult(param);
        return Result.succeed(result);
    }

    /**
     * 执行分析
     */
    @RequestMapping("/previewPageResult")
    @PreAuthorize("hasAnyAuthority('audit_model:auditmodel:previewResult')")
    public AuditModelBaseResult previewPageResult(@RequestParam Map<String, Object> param) {
        String modelId = param.get("modelId").toString();
        String warnId = param.containsKey("warnId") ? param.get("warnId").toString() : null;

        AuditModelBaseResult result = auditModelService.previewResult(param);
        return result;
    }

    /**
     * 执行分析-- 大屏对外接口
     */
    @RequestMapping("/jsonResult")
    public Result jsonResult(@RequestParam Map<String, Object> param) {
        String modelId = param.get("modelId").toString();
        String warnId = param.containsKey("warnId") ? param.get("warnId").toString() : null;
        AuditModel model = auditModelService.findById(modelId);

        AuditModelBaseResult result = auditModelService.previewResult(param);
        return Result.succeed(result);
    }


    /**
     * 导出数据
     */
    @RequestMapping("/exportExcel")
    @PreAuthorize("hasAnyAuthority('audit_model:auditmodel:export')")
    public void exportExcel(@RequestParam Map<String, Object> param, HttpServletResponse response) {
        String modelId = param.get("modelId").toString();
        String warnId = param.containsKey("warnId") ? param.get("warnId").toString() : null;
        AuditModel model = auditModelService.findById(modelId);

        auditModelService.exportExcel(param, response);
    }

}
